/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.utils;

import org.apache.commons.lang3.ObjectUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Class工具类
 *
 * @auther ebert_chan
 */
public class ClassUtils {

    /**
     * 创建类的新实例，调用类构造方法，确保构造参数中不能出现null值，并且参数值类型必须与构造方法参数类型匹配
     *
     * @param classes
     * @param initargs
     * @return
     * @throws Exception
     * @auther ebert_chan
     */
    public static <T> T newInstance(Class<T> classes, Object... initargs) throws Exception {
        Constructor<T> constructor;
        if (initargs.length == 0) {
            constructor = classes.getConstructor();
            return constructor.newInstance();
        }

        Class<?>[] parameterTypes = new Class[initargs.length];
        for (int i = 0; i < initargs.length; i++) {
            parameterTypes[i] = initargs[i].getClass();
        }
        return newInstance(classes, parameterTypes, initargs);
    }

    /**
     * 创建类的新实例，调用类有参构造方法
     *
     * @param classes
     * @param parameterTypes
     * @param initargs
     * @return
     * @throws Exception
     * @auther ebert_chan
     */
    public static <T> T newInstance(Class<T> classes, Class<?>[] parameterTypes, Object[] initargs) throws Exception {
        if (parameterTypes == null) {
            return newInstance(classes);
        }
        Constructor<T> constructor = classes.getConstructor(parameterTypes);
        return constructor.newInstance(initargs);
    }

    /**
     * 反射获取类方法
     *
     * @param classes
     * @param name
     * @param parameterTypes
     * @return
     * @auther ebert_chan
     */
    public static Method getAccessibleMethod(Class<?> classes, String name, Class<?>... parameterTypes) {
        Method method = null;
        try {
            method = classes.getMethod(name, parameterTypes);
            if (method != null) {
                method.setAccessible(true);
            }
        } catch (NoSuchMethodException | SecurityException e) {
            // ignore exception
        }
        return method;
    }

    /**
     * 获取对应方法的返回值，如调用方法出现异常，则返回null
     *
     * @param method
     * @param obj
     * @param args
     * @return
     * @auther ebert_chan
     */
    public static Object invokeOrNull(Method method, Object obj, Object... args) {
        try {
            return method.invoke(obj, args);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            // ignore exception
        }
        return null;
    }

    /**
     * 对象所有成员变量进行比较，如对象中有引用其他类实例作为其成员变量，需要重写其他类的equals方法
     *
     * @param t1
     * @param t2
     * @return
     * @auther ebert_chan
     */
    public static boolean isAllFiledsEqual(Object object1, Object object2) {
        if (object1 == object2) {
            return true;
        }
        if (object1 == null || object2 == null) {
            return false;
        }
        if (!object1.getClass().equals(object2.getClass()) || !object1.getClass().isAssignableFrom(object2.getClass())) {
            return false;
        }

        Class<?> classes = object1.getClass();
        List<Method> methodList = getFieldGetterMethods(classes);
        for (Method method : methodList) {
            Object value1 = invokeOrNull(method, object1);
            Object value2 = invokeOrNull(method, object2);
            if (ObjectUtils.notEqual(value1, value2)) {
                return false;
            }
        }

        return true;
    }

    /**
     * 获取类所有的Getter方法
     *
     * @param classes
     * @return
     * @auther ebert_chan
     */
    public static List<Method> getFieldGetterMethods(Class<?> classes) {
        Field[] fields = classes.getFields();
        if (fields == null) {
            return null;
        }
        Method[] methods = getAllMethods(classes);
        if (methods == null) {
            return null;
        }
        List<Method> methodList = new ArrayList<>();
        for (Field field : fields) {
            Method getter = toGetterMethod(classes, field);
            if (getter == null) {
                continue;
            }
            if (!getter.getReturnType().equals(Void.TYPE)) {
                methodList.add(getter);
                break;
            }
        }
        return methodList;
    }

    /**
     * 成员变量转换为Getter方法名称
     *
     * @param field
     * @return
     * @auther ebert_chan
     */
    public static Method toGetterMethod(Class<?> classes, Field field) {
        String name = field.getName();
        char[] c = name.toCharArray();
        c[0] = new String(new char[]{c[0]}).toUpperCase().charAt(0);

        if (field.getType().equals(Boolean.TYPE)) {
            name = "is" + new String(c);
            Method method = getMethod(classes, name);
            if (method != null) {
                return method;
            }
        }
        name = "get" + new String(c);
        Method method = getMethod(classes, name);
        return method;
    }

    /**
     * 获取类所有方法
     *
     * @param classes
     * @return
     * @auther ebert_chan
     */
    public static Method[] getAllMethods(Class<?> classes) {
        Method[] methods = classes.getMethods();
        return methods;
    }

    /**
     * 通过方法名获取类方法
     *
     * @param classes
     * @return
     * @auther ebert_chan
     */
    public static Method getMethod(Class<?> classes, String name, Class<?>... parameterTypes) {
        Method method = null;
        try {
            method = classes.getMethod(name, parameterTypes);
        } catch (NoSuchMethodException | SecurityException e) {
            // ignore exception
        }
        return method;
    }

}
